class Game {
	init(width, height, max) {
		this.width = width
		this.height = height
		this.max = max
		this.size = this.width * this.height
		this.status = new Array(this.size).fill(1)
		this.history = new Array(this.size).fill(0)
		this.initclicks = new Array(this.size).fill(0)
		this.clicks = new Array(this.size).fill(0)
		this.isFinished = false
		this.bestClickCount = 0
		this.clickCount = 0
		// for (let i = 0; i < this.size; i++) {
		// 	let d = parseInt(Math.random() * this.max)
		// 	if (d > 0) {
		// 		this.history[i] = d
		// 		let x = i % this.width
		// 		let y = parseInt(i / this.width)
		// 		this.change(x, y, d)
		// 		this.change(x, y + 1, d)
		// 		this.change(x, y - 1, d)
		// 		this.change(x + 1, y, d)
		// 		this.change(x - 1, y, d)
		// 	}
		// }
		console.log(this.width, this.height, this.status, this.history)
	}

	change(x, y, val = 1) {
		if (x < 0 || x >= this.width) {
			return
		}
		if (y < 0 || y >= this.height) {
			return
		}
		let id = y * this.width + x
		let v = this.status[id] + val
		if (v > this.max) {
			v = v % this.max
		}
		this.status[id] = v
	}

	click(id) {
		this.clicks[id]=(this.clicks[id]+1)%9
		// this.clicks[id]++
		this.clickCount++
		let x = id % this.width
		let y = parseInt(id / this.width)
		this.change(x, y)
		this.change(x, y + 1)
		this.change(x, y - 1)
		this.change(x + 1, y)
		this.change(x - 1, y)
		this.check()
	}

	check() {
		let v = this.status[0]
		let bcc = this.clicks[0]
		for (let i = 1; i < this.size; i++) {
			if (this.status[i] != v) {
				return false
			}
			bcc += this.clicks[i] % this.max
		}
		this.isFinished = true
		this.bestClickCount = bcc
		return true
	}

	test() {
		console.log(this.clickCount, this.clicks, this.status)
	}
}